package com.ambow.shop.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ambow.shop.action.Action;
import com.ambow.shop.action.impl.AddAuthorizationAction;
import com.ambow.shop.action.impl.ToAddAuthorizationAction;
import com.ambow.shop.action.impl.DefaultAction;
import com.ambow.shop.action.impl.RemoveAuthorizationAction;

/**
 * 授权控制器。
 * 
 * @author chunw
 *
 */
@WebServlet(name = "AuthorizationController", urlPatterns = "/authorization/*")
public class AuthorizationController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public AuthorizationController() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		process(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		process(request, response);
	}

	private String getActionName(String uri) {
		return uri.substring(uri.lastIndexOf("/") + 1);
	}

	private void process(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Action action = null;
		String actionName = getActionName(request.getRequestURI());

		if ("add".equals(actionName)) { // 登入；
			action = new AddAuthorizationAction();
		} else if ("remove".equals(actionName)) { // 登出；
			action = new RemoveAuthorizationAction();
		} else if ("toAdd".equals(actionName)) { // 检查；
			action = new ToAddAuthorizationAction();
		} else {
			action = new DefaultAction();
		}

		String result = action.execute(request, response);
		if (result.equals("/home")) {
			response.sendRedirect(result);
		} else {
			request.getRequestDispatcher(result).forward(request, response);
		}
	}
}
